package com.atguigu.gulimall.ware.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @Description: 统一异常处理器
 * @Author 胡菜鸡
 * @Create 2021-12-28-15:08
 */
@Slf4j
//处理此包下发生的异常，并将异常消息以JSON返回
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.ware.controller")
public class WareExceptionControllerAdvice {

    /**
     * 统一处理数据校验异常
     *
     * @author 胡菜鸡
     * @date 2021/12/17 15:15
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)  //说明需要处理的异常类型
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();

        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", errorMap);
    }

    /**
     * 处理自定义异常
     *
     * @author 胡菜鸡
     * @date 2021/12/28 15:24
     */
    @ExceptionHandler(RRException.class)
    public R handleRRException(RRException e) {

        return R.error(e.getCode(),e.getMsg());
    }

    /**
     * 统一处理任意类型异常
     *
     * @author 胡菜鸡
     * @date 2021/12/17 15:17
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {

        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
